package com.cxx.admin.service.impl;


import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxx.admin.service.AccountService;
import com.cxx.admin.dao.AccountDao;
import com.cxx.common.dto.AccountDto;
import com.cxx.common.entity.Account;
import com.cxx.common.entity.User;
import com.cxx.common.mapper.AccountMapper;
import com.cxx.common.mapper.UserMapper;
import com.cxx.framework.web.CustomException;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public List<AccountDto> queryAccountList() {
        return accountDao.queryAccount();
    }

    @Override
    public Account queryAccountByUserId(Long userId) {
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        return accountMapper.selectOne(queryWrapper.eq(Account::getUserId, userId));
    }

    @Transactional
    @Override
    public Boolean registerAccount(AccountDto accountDto) {
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        if (accountMapper.exists(queryWrapper.eq(Account::getAccountName, accountDto.getAccountName()))) {
            throw new CustomException("该账户已经存在");
        }

        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        if (userMapper.exists(userQueryWrapper.eq(User::getUsername, accountDto.getUsername()))) {
            throw new CustomException("该用户已注册");
        }

        List<Integer> results = new ArrayList<>();
        User user = new User();
        BeanUtils.copyProperties(accountDto, user);
        results.add(userMapper.insert(user));

        Account account = new Account();
        account.setAccountName(accountDto.getAccountName());
        account.setPassword(BCrypt.hashpw(accountDto.getPassword(), BCrypt.gensalt()));
        account.setUserId(user.getId());
        account.setState(0);
        results.add(accountMapper.insert(account));

        return results.stream().allMatch(x -> x > 0);
    }

    @Override
    public Boolean deleteAccount(Long id) {
        Account account = accountMapper.selectById(id);

        if (account == null) {
            throw new CustomException("该账号不存在");
        }

        accountMapper.deleteById(id);
        return userMapper.deleteById(account.getUserId()) == 1;
    }
}
